//
//  THPublishTaskVC.m
//  YJB
//
//  Created by YJB on 2016/11/25.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THPublishTaskVC.h"
#import "YJUserDefaultTool.h"
#import "YJNetworkTool.h"
#import "YJGlobalHeader.h"
#import "THTaskProtocolVC.h"

@interface THPublishTaskVC ()<UIScrollViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *taskTitle;
@property (weak, nonatomic) IBOutlet UITextField *url;
@property (weak, nonatomic) IBOutlet UITextField *total;
@property (weak, nonatomic) IBOutlet UITextField *price;
@property (weak, nonatomic) IBOutlet UITextField *requireGlod;
@property (weak, nonatomic) IBOutlet UIView *containView;
@property (weak, nonatomic) IBOutlet UIButton *publishBtn;
@property (weak, nonatomic) IBOutlet UIButton *checkProtocolBtn;

@end

@implementation THPublishTaskVC

- (void)getPrice
{
    [MBProgressHUD showMessage:@"正在获取单价" toView:nil];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    
    params[@"action"] = @"get_publishgold_one";
    params[@"makegold"] = @{@"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    [YJNetworkTool postWithUrl:THURL(@"traffic.php") parameters:params success:^(id responseObject) {
        NSString *code = responseObject[@"return"][@"code"];
        [MBProgressHUD hideHUDForView:nil];
        if (code.integerValue == 200)
        {
            NSDictionary *dict = [[responseObject objectForKey:@"return"] objectForKey:@"data"];
            NSString *price = [dict objectForKey:@"gold_one"];
            self.price.text = price;
            self.price.enabled = NO;
        }else {
            NSString *message = responseObject[@"return"][@"message"];
            [MBProgressHUD showError:message toView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:nil];
    }];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == self.total) {
        self.requireGlod.text = [NSString stringWithFormat:@"%.2f",[self.price.text floatValue]*[self.total.text floatValue]];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self getPrice];
    self.total.delegate = self;
    self.title = @"发布任务";
    self.checkProtocolBtn.selected = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    @weakify(self)
    [tap.rac_gestureSignal subscribeNext:^(id x) {
       @strongify(self)
        [self.containView endEditing:YES];
    }];
    [_containView addGestureRecognizer:tap];
    NSArray *textFields = @[_taskTitle,_url,_total,_price,_requireGlod];
    for (int i = 0; i < textFields.count; i ++)
    {
        UIView *leftView = [[UIView alloc]init];
        leftView.width = 4;
        UITextField *textField = textFields[i];
        textField.leftView = leftView;
        textField.leftViewMode = UITextFieldViewModeAlways;
    }
    
   RAC(self.requireGlod,text) = [[RACSignal combineLatest:@[_price.rac_textSignal,_total.rac_textSignal] reduce:^id(NSString *price,NSString *total){
        return [@(price.doubleValue * total.doubleValue) stringValue ];
    }] skip:1];
    
}

- (IBAction)publishBtn:(UIButton *)button
{
    NSArray *messages = @[@"请输入任务标题",@"请输入任务地址",@"请输入任务总量",@"请输入单价"];
    NSArray *textFields = @[_taskTitle,_url,_total,_price];
    for (int i = 0; i < messages.count ; i ++)
    {
        UITextField *textField = textFields[i];
        if (textField.text.length == 0)
        {
            [MBProgressHUD showError:messages[i]];
            return;
        }
        if (i == 1 && ![textField.text isUrlString])
        {
            [MBProgressHUD showError:@"任务地址格式不对"];
            return;
        }
    }
    [self publishTask];
}

#pragma mark - 最新发布接口（62）
- (void)publishTask{
    
    [MBProgressHUD showMessage:@""];
    NSString *strTest = [[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key];
    NSString *keyStr = [strTest md5];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"set_cpcclick_add";
    params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
                            @"adv_title":_taskTitle.text,
                            @"adv_url":_url.text,
                            @"adv_icon":@"",
                            @"total_num":_total.text,
                            @"gold_one":_price.text,
                            @"operate_need":@"",
                            @"method":@"2",
                            @"ans_match1":@"2",
                            @"ans_result1":@"",
                            @"ans_request1":@"",
                            @"user_info":@"admin",
                            @"phone_info":@"iOS",
                            @"md5_key":keyStr,
                            };
    
    [YJNetworkTool postWithUrl:THURL(@"cpcclick.php") parameters:params success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        if ([responseObject[@"return"][@"code"] integerValue] == 200)
        {
            [MBProgressHUD showSuccess:@"发布成功"];
            if (self.userDidPublishBlock)
                self.userDidPublishBlock();
            
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            NSString *message = responseObject[@"return"][@"message"];
            [MBProgressHUD showError:message toView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络不佳,稍后重试" toView:self.view];
    }];
}

//- (void)publishTask{
//    
//    [MBProgressHUD showMessage:@""];
//    NSString *strTest = [[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:Md5Key];
//    NSString *keyStr = [strTest md5];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"action"] = @"set_surf_add";
//    params[@"makegold"] = @{@"username":[YJUserDefaultTool readUserName],
//                            @"sitename":_taskTitle.text,
//                            @"url":_url.text,
//                            @"surflimit":_total.text,
//                            @"price":_price.text,
//                            @"user_info":@"admin",
//                            @"phone_info":@"iOS",
//                            @"md5_key":keyStr,
//                            };
//    
//    [YJNetworkTool postWithUrl:THURL(@"traffic.php") parameters:params success:^(id responseObject) {
//        [MBProgressHUD hideHUD];
//        if ([responseObject[@"return"][@"code"] integerValue] == 200)
//        {
//            [MBProgressHUD showSuccess:@"发布成功"];
//            if (self.userDidPublishBlock)
//                self.userDidPublishBlock();
//            
//            [self.navigationController popViewControllerAnimated:YES];
//        }else
//        {
//            NSString *message = responseObject[@"return"][@"message"];
//            [MBProgressHUD showError:message toView:self.view];
//        }
//    } failure:^(NSError *error) {
//        [MBProgressHUD hideHUD];
//        [MBProgressHUD showError:@"网络不佳,稍后重试" toView:self.view];
//    }];
//}


- (IBAction)cancelBtn:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (IBAction)checkTaskProtocol:(UIButton *)button
{
    button.selected = !button.selected;
    self.publishBtn.enabled = button.selected;
}

- (IBAction)protocolBtnClick:(UIButton *)button
{
    [self.navigationController pushViewController:[THTaskProtocolVC new] animated:YES];
}



@end
